import { useState, useRef, useEffect } from 'react'
import { useDispatch, useSelector } from "react-redux"
import { Link } from 'react-router-dom'
import UserService from '../../app/services/userService'
import CryptHelper from '../../utils/encrypted'
import { setUserInfo } from '../../app/store/userinfoSlice'
import ErrorText from '../../components/Typography/ErrorText'
import InputText from '../../components/Input/InputText'
import { useNavigate } from 'react-router-dom';
import Particles, { initParticlesEngine } from "@tsparticles/react";
import { loadSlim } from "@tsparticles/slim";

function Login() {

    const INITIAL_LOGIN_OBJ = {
        loginName: "",
        password: ""
    }
    const dispatch = useDispatch()
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false)
    const [errorMessage, setErrorMessage] = useState("")
    const [loginObj, setLoginObj] = useState(INITIAL_LOGIN_OBJ)

    const [init, setInit] = useState(false);

    // this should be run only once per application lifetime
    useEffect(() => {
        initParticlesEngine(async (engine) => {
            // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
            // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
            // starting from v2 you can add only the features you need reducing the bundle size
            //await loadAll(engine);
            //await loadFull(engine);
            await loadSlim(engine);
            //await loadBasic(engine);
        }).then(() => {
            setInit(true);
        });
    }, []);

    const submitForm = (e) => {
        e.preventDefault()

        if (loginObj.loginName.trim() === "") return setErrorMessage("登录名不能为空")
        if (loginObj.password.trim() === "") return setErrorMessage("登录密码不能为空")
        else {
            setLoading(true)
            UserService.login({
                loginName: loginObj.loginName,
                password: CryptHelper.encryptWithMd5(loginObj.password)
            }).then(response => {
                if (response.success) {
                    localStorage.setItem("token", `Bearer  ${response.data.token}`)
                    const uerInfo = { ...response.data, ticket: new Date().getTime() }
                    dispatch(setUserInfo(uerInfo))
                    navigate('/app/mineUser')
                }
            }).catch(error => {
                console.log(error)
                setErrorMessage(error)
            }).finally(() => {
                setLoading(false)
            })
        }
    }

    const particlesLoaded = (container) => {
    };

    const updateFormValue = ({ updateType, value }) => {
        setErrorMessage("")
        setLoginObj({ ...loginObj, [updateType]: value })
    }

    return (
        <>
            <div className="min-h-screen bg-base-200 flex items-center">
                <div className="card mx-auto w-full max-w-xl  shadow-xl z-50">
                    <div className="flex flex-row items-center justify-center bg-base-100 rounded-xl">
                        <div className='py-12 px-4'>
                            <div className='flex flex-col items-center justify-center'>
                                <div className='flex flex-col items-center justify-center'>
                                    <img  style={{width:'120px', height:'120px'}} src="/logo_big.svg" alt="大鱼选校" />
                                    <img   style={{width:'188px', height:'44px'}} src="/label.png" alt="大鱼选校" />
                                </div>
                                <form onSubmit={(e) => submitForm(e)} style={{ width: '400px' }}>
                                    <div className="mb-4">
                                        <InputText type="emailId" defaultValue={loginObj.loginName} updateType="loginName" containerStyle="mt-4" labelTitle="登录名" updateFormValue={updateFormValue} />
                                        <InputText defaultValue={loginObj.password} type="password" updateType="password" containerStyle="mt-4" labelTitle="密码" updateFormValue={updateFormValue} />
                                    </div>

                                    <div className='text-right text-primary'><Link to="/forgot-password"><span className="text-sm  inline-block  hover:text-primary hover:underline hover:cursor-pointer transition duration-200">忘记密码</span></Link>
                                    </div>

                                    <ErrorText styleClass="mt-8">{errorMessage}</ErrorText>
                                    <button type="submit" className={"btn mt-2 w-full btn-primary" + (loading ? " loading" : "")}>登录</button>

                                </form>
                            </div>
                        </div>
                    </div>
                    <div className='fixed bottom-0  inset-x-0 h-12 p-4'>
                        <div className='text-center text-xs'>备案号:<Link to="https://beian.miit.gov.cn/"><button className="  inline-block  hover:text-primary hover:underline hover:cursor-pointer transition duration-200">冀ICP备15004512号</button></Link></div>
                    </div>
                </div>

                {init && <Particles
                    id="tsparticles"
                    particlesLoaded={particlesLoaded}
                    options={{
                        background: {
                            color: {
                                value: "#000000",
                            },
                        },
                        fpsLimit: 120,
                        interactivity: {
                            events: {
                                onClick: {
                                    enable: true,
                                    mode: "push",
                                },
                                onHover: {
                                    enable: true,
                                    mode: "repulse",
                                },
                                resize: true,
                            },
                            modes: {
                                push: {
                                    quantity: 4,
                                },
                                repulse: {
                                    distance: 200,
                                    duration: 0.4,
                                },
                            },
                        },
                        particles: {
                            color: {
                                value: "#ffffff",
                            },
                            links: {
                                color: "#ffffff",
                                distance: 150,
                                enable: true,
                                opacity: 0.5,
                                width: 1,
                            },
                            move: {
                                direction: "none",
                                enable: true,
                                outModes: {
                                    default: "bounce",
                                },
                                random: true,
                                speed: 3,
                                straight: true,
                            },
                            number: {
                                density: {
                                    enable: true,
                                    area: 800,
                                },
                                value: 80,
                            },
                            opacity: {
                                value: 0.2,
                            },
                            shape: {
                                type: "circle",
                            },
                            size: {
                                value: { min: 1, max: 5 },
                            },
                        },
                        detectRetina: true,
                    }}
                ></Particles>}
            </div>
        </>
    )
}

export default Login